package com.example.drive

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.drive.bean.DrivingQuestionBean
import com.example.drive.bean.ResultBean
import com.example.drive.db.JZTKDataBase
import com.example.drive.net.asyncRequest
import com.example.drive.net.callback.EntityCallback
import com.example.drive.net.request.FormRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 驾照题库ViewModel
 */
class JZTKViewModel : ViewModel() {
    companion object {
        private const val TAG = "JZTKViewModel"
        private const val URL = "https://v.juhe.cn/jztk/query"
        private const val KEY = "912c3c1075b6458aa6ffa84bb7162c6a"
    }

    var resultBeanList = MutableLiveData<List<ResultBean>?>()

    private val params: MutableMap<String, String> by lazy {
        mutableMapOf(
            "subject" to "1",
            "key" to KEY,
            "model" to "c1",
            "testType" to "order"
        )
    }

    /**
     * 查询驾照题库
     */
    fun queryJZTK() {
        // 先从本地数据库获取
        queryJZTKFromDatabase {
            if (this == null || this.isEmpty()) {
                // 本地没有数据,从云端获取
                queryJZTKFromCloud()
            } else {
                // 本地有数据
                Log.d(TAG, "本地有数据")
                resultBeanList.postValue(this)
            }
        }
    }

    /**
     * 从云端查询驾照题库
     */
    private fun queryJZTKFromCloud() {
        Log.d(TAG, "queryJZTKFromCloud")
        FormRequest(URL, this, params).asyncRequest(object :
            EntityCallback<DrivingQuestionBean?>() {
            override fun onResponse(data: DrivingQuestionBean?) {
                // 将驾考题库数据保存至本地数据库
                data?.result?.let {
                    resultBeanList.postValue(it)
                    viewModelScope.launch(Dispatchers.IO) {
                        val longs = JZTKDataBase.resultBeanDao.insertAll(it)
                        Log.d(TAG, "longs = $longs")
                    }
                }
            }

            override fun onFailure(throwable: Throwable) {

            }
        })
    }

    /**
     * 从本地数据库查询驾照题库
     */
    private fun queryJZTKFromDatabase(result: List<ResultBean>?.() -> Unit) {
        Log.d(TAG, "queryJZTKFromDatabase")
        // 必须在子线程访问数据库,否者会报错
        // Cannot access database on the main thread since it may potentially lock the UI for a long period of time
        viewModelScope.launch(Dispatchers.IO) {
            val start = System.currentTimeMillis()
            val list = JZTKDataBase.resultBeanDao.queryAll()
            val end = System.currentTimeMillis()
            Log.d(TAG, "查询本地数据库耗时:${end - start}ms")
            result.invoke(list)
        }
    }
}